#!/usr/bin/env bash
# vim: fdm=marker fmr=[[[,]]] cms=\ #%s

bin_path=$(dirname $0)
if [ ${bin_path:0:1} != '/' ]
then
    bin_path=$(pwd)/$bin_path
fi
CLIENT=$bin_path/../../tool/snclient
ADDR=localhost:10020

CREATE()
{ #[[[
    local uuid
    read -p "uuid[@00000000001]: " uuid
    $CLIENT $ADDR CREATE "${uuid:-@00000000001}"
} #]]]

GET()
{ #[[[
    local uuid
    read -p "uuid[@00000000001]: " uuid
    $CLIENT $ADDR GET "${uuid:-@00000000001}"
} #]]]

VALIDATE()
{ #[[[
    local sid
    read -p "sid: " sid
    $CLIENT $ADDR VALIDATE "${sid}"
} #]]]

DESTROY()
{ #[[[
    local sid
    read -p "sid: " sid
    $CLIENT $ADDR DESTROY "${sid}"
} #]]]

PUTKEY()
{ #[[[
    local sid
    read -p "sid: " sid
    local key1
    local val1
    read -p "key1[key1]: " key1
    read -p "val1[100]: " val1
    local key2
    local val2
    read -p "key2[key2]: " key2
    read -p "val2[hello world]: " val2
    $CLIENT $ADDR PUTKEY "${sid}" 2 "${key1:-key1}" "${val1:-100}" "${key2:-key2}" "${val2:-hello world}"
} #]]]

GETKEY()
{ #[[[
    local sid
    read -p "sid: " sid
    local key1
    read -p "key1[key1]: " key1
    local key2
    read -p "key2[key2]: " key2
    $CLIENT $ADDR GETKEY "${sid}" 2 "${key1:-key1}" "${key2:-key2}"
} #]]]

MODKEY()
{ #[[[
    local sid
    read -p "sid: " sid
    local key
    read -p "key[key1]: " key
    local delta
    read -p "delta[-1]: " delta
    $CLIENT $ADDR MODKEY "${sid}" "${key:-key1}" "${delta:--1}"
} #]]]

DESTROYKEY()
{ #[[[
    local sid
    read -p "sid: " sid
    local key
    read -p "key[key1]: " key
    $CLIENT $ADDR DESTROYKEY "${sid}" "${key:-key1}"
} #]]]

ENCRYPT()
{ #[[[
    local plain
    local plain_def="http://site.com/login.php?action=somework"
    read -p "plain[$plain_def]: " plain
    $CLIENT $ADDR ENCRYPT "${plain:-$plain_def}"
} #]]]

DECRYPT()
{ #[[[
    local enc
    read -p "enc: " enc
    $CLIENT $ADDR DECRYPT "${enc}"
} #]]]

main()
{ #[[[
    if [[ ! -x $CLIENT ]]
    then
        echo "snclient not found"
        return 1
    fi

    local option
    read -p "\
Available services:
    1) CREATE uuid
    2) GET uuid
    3) VALIDATE sid
    4) DESTROY sid
    5) PUTKEY sid key_num { key val }
    6) GETKEY sid key_num { key }
    7) MODKEY sid key delta
    8) DESTROYKEY sid key
    9) ENCRYPT url
    a) DECRYPT urlenc
Input: " option
    if [[ -z $option ]]
    then
        echo  "Error: option invalid"
        return 1
    fi
    case $option in
    1) CREATE ;;
    2) GET ;;
    3) VALIDATE ;;
    4) DESTROY ;;
    5) PUTKEY ;;
    6) GETKEY ;;
    7) MODKEY ;;
    8) DESTROYKEY ;;
    9) ENCRYPT ;;
    a) DECRYPT ;;
    *)
        echo "Error: option($option) not supported"
        return 1
        ;;
    esac
} #]]]

main
exit $?
